﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;

namespace App
{
    static class Program
    {
        private static Mutex m_Instance;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.DoEvents();
            m_Instance = new Mutex(true, "App2015");
            string arg = String.Empty;
            if(args.Length > 0)
            {
                arg = args[0];
            }
            Startup.GetApp();
            Application.Run();
            //if (1 == 1) //(arg == "clone" || _instance.WaitOne(0, false))
            //{
            //    Startup startup = Startup.GetApp();
            //    Thread threadBack = new Thread(new ThreadStart(collectGarbage));
            //    threadBack.Name = "ThreadBackground";
            //    threadBack.IsBackground = true;
            //    threadBack.Start();
            //    Application.Run();
            //    startup = null;
            //}
            //else
            //{
            //    foreach (System.Diagnostics.Process proc in System.Diagnostics.Process.GetProcessesByName(
            //        System.Diagnostics.Process.GetCurrentProcess().ProcessName))
            //    {
            //        if (proc.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
            //        {
            //            //						Util.WindowsMessaging.AlertOtherInstance();
            //            //						break;
            //        }
            //    }
            //}
        }


        #region CollectGarbage
        public static void CollectGarbage()
        {
            try
            {
                GC.WaitForPendingFinalizers();
                GC.Collect();
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                }
            }
            catch { }
        }
        #endregion

        #region collectGarbage
        private static void collectGarbage()
        {
            while (true)
            {
                Application.DoEvents();
                CollectGarbage();
                Thread.Sleep(10000);
            }
        }
        #endregion

        #region SetProcessWorkingSetSize
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(
            IntPtr hProcess,
            int dwMinimumWorkingSetSize,
            int dwMaximumWorkingSetSize
            );
        #endregion
    }
}
